package com.didojoy.lameliarary;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

import com.didojoy.lameliarary.listener.RecorderListener;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by weiwei42 on 2018/1/22.
 */

public class Mp3Recorder {
    private static final String TAG = Mp3Recorder.class.getSimpleName();
    public static final int NUM_CHANNELS = 1;
    public static final int SAMPLE_RATE = 16000;
    public static final int BITRATE = 128;

    private AudioRecord mRecorder;
    private short[] mBuffer;
    private boolean mIsRecording = false;
    private RecorderListener mListener;
    private ExecutorService mExecutorService = Executors.newCachedThreadPool();

    public Mp3Recorder(RecorderListener listener) {
        mListener = listener;
        initRecorder();
    }

    public void start(File file) {
        if (mIsRecording) {
            if (mListener != null) {
                mListener.onRecorderError(null);
            }
            return;
        }

        if (mRecorder != null && mRecorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
            if (mListener != null) {
                mListener.onRecorderError(null);
            }
            return;
        }

        if (mRecorder == null) {
            initRecorder();
        }

        mRecorder.startRecording();
        startBufferedWrite(file);
    }

    public void stop() {
        if (mRecorder != null && mIsRecording) {
            mIsRecording = false;
        } else {
            if (mListener != null) {
                mListener.onRecorderError(null);
            }

            if (mRecorder != null) {
                try {
                    mRecorder.stop();
                    mRecorder.release();
                    mRecorder = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        mExecutorService.shutdown();
    }

    private void initRecorder() {
        try {
            int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);
            mBuffer = new short[bufferSize];
            mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, bufferSize);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    private void startBufferedWrite(final File file) {
        if (file == null) {
            if (mListener != null) {
                mListener.onRecorderError(null);
            }
            return;
        }

        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                mIsRecording = true;

                DataOutputStream output = null;
                try {
                    output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                    while (mIsRecording) {
                        int readSize = mRecorder.read(mBuffer, 0, mBuffer.length);
                        for (int i = 0; i < readSize; i++) {
                            output.writeShort(mBuffer[i]);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "recorder error1: " + e.getMessage(), e);
                    if (mListener != null) {
                        mListener.onRecorderError(null);
                        return;
                    }
                    e.printStackTrace();
                } finally {
                    if (output != null) {
                        try {
                            output.flush();
                        } catch (IOException e) {
                            Log.e(TAG, "recorder error2: " + e.getMessage(), e);
                            e.printStackTrace();
                        } finally {
                            try {
                                output.close();
                            } catch (IOException e) {
                                Log.e(TAG, "recorder error3: " + e.getMessage(), e);
                                e.printStackTrace();
                            }
                        }
                    }

                    if (mRecorder != null) {
                        try {
                            mRecorder.stop();
                            mRecorder.release();
                            mRecorder = null;
                        } catch (Exception e) {
                            Log.e(TAG, "recorder error4: " + e.getMessage(), e);
                            e.printStackTrace();
                        }
                    }
                }

                if (file.length() > 0) {
                    if (mListener != null) {
                        mListener.onRecorderSucc(file.getAbsolutePath());
                    }
                } else {
                    if (mListener != null) {
                        mListener.onRecorderError(null);
                    }
                }

            }
        });

    }

}
